package com.zx.练习题._2022面试题;

import lombok.extern.slf4j.Slf4j;

/**
 * 写一个程序，由两个线程协作，按顺序打印出 1-10，其中一个线程打印奇数，另一个线程打印偶数，且两个线程要交替工作；
 * 例： A 线程打印1，之后B 线程打印2，之后 A 线程打印 3，之后 B 线程打印 4……，直至 1-10
 * 全部打印完毕；
 */
@Slf4j
public class Demo4 {

    private static int counter = 1;
    private static Object lock = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            while (counter <= 9) {
                synchronized (lock) {
                    if (counter % 2 != 0) {
                        log.info("{}", counter);
                        counter++;
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "奇数").start();

        new Thread(() -> {
            while (counter <= 10) {
                synchronized (lock) {
                    if (counter % 2 == 0) {
                        log.info("{}", counter);
                        counter++;
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "偶数").start();
    }
}
